package com.zoo.wuhua.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description
 * @author zhangli7@yusys.com.cn
 * @since 2020年1月22日 下午5:36:20 v1.0
 */
@RestController
public class GenerateMenuController {

    private static final Pattern PATTERN = Pattern.compile("<h4>(\\d+)\\.(.+)</h4>");
    private static Map<String, String> map;

    static {
        map = new LinkedHashMap<String, String>();
        map.put("util", "实用工具");
        map.put("html", "HTML5");
        map.put("css", "CSS3");
    }

    @RequestMapping("/menu")
    public String genMenu() throws IOException {
        StringBuffer sb = new StringBuffer();
        for (Entry<String, String> entry : map.entrySet()) {
            String folderName = entry.getKey();
            String path = "C:\\Users\\张丽\\git\\html5\\WebContent\\" + folderName;
            File file = new File(path);
            File[] files = file.listFiles();
            sb.append("<h4>" + entry.getValue() + "</h4><ul>");
            String[] list = new String[files.length];
            for (File f : files) {
                List<String> lines = Files.readAllLines(Paths.get(f.getAbsolutePath()));
                for (String line : lines) {
                    Matcher matcher = PATTERN.matcher(line);
                    if (matcher.matches()) {
                        String url = f.getName();
                        String seqNo = matcher.group(1);
                        String title = matcher.group(2);
                        String link = "<li><a href=\"javascript: void(0);\" data-url=\"./" + folderName + "/" + url
                                + "\">" + title + "</a></li>";
                        list[Integer.parseInt(seqNo) - 1] = link;
                    }
                }
            }
            for (String li : list) {
                sb.append(li);
            }
            sb.append("</ul>");
        }
        return sb.toString();
    }
}
